﻿using mozhi.smarterp.BasicData.DataLinkages.Events;
using System;
using System.Collections.Generic;
using System.Text;
using Volo.Abp;

namespace mozhi.smarterp.BasicData.Employees
{
    public class Employee : AggregateRootBase
    {
        public string Phone { get; private set; }

        public string Email {  get; private set; }

        /// <summary>
        /// 部门
        /// </summary>
        public Guid? DepartmentId { get; private set; }

        private Employee() { }

        public Employee(Guid id, string code, string name, Guid? departmentId, string phone , string email , bool activated) : base(id, code, name , activated)
        {
            Phone = phone;
            Email = email;
            DepartmentId = departmentId;

            if (departmentId.HasValue)
                AddDistributedEvent(GetAuthorCenterDataLinkageCreateEvent(departmentId.Value, "Department"));

            Validate();
        }

        public void Change(string code, string name, Guid? departmentId, string phone, string email, bool activated)
        {
            base.Change(code, name, activated);

            var departmentEqual = DepartmentId == departmentId;

            if (!departmentEqual)
            {
                if (DepartmentId.HasValue)
                    AddDistributedEvent(GetAuthorCenterDataLinkageDeleteEvent(DepartmentId.Value));

                if (departmentId.HasValue)
                    AddDistributedEvent(GetAuthorCenterDataLinkageCreateEvent(departmentId.Value, "Department"));
            }

            DepartmentId = departmentId;
            Phone = phone;
            Email = email;

            Validate();

          
        }

        #region
        protected override void Validate()
        {
            base.Validate();

            Check.NotNullOrEmpty(Phone , nameof(Phone));

            Check.NotNullOrEmpty(Email, nameof(Email));

            Check.NotDefaultOrNull(DepartmentId, nameof(DepartmentId));
        }

        private AuthorCenterDataLinkageCreateEvent GetAuthorCenterDataLinkageCreateEvent(Guid providerId, string providerType)
        {
            return new AuthorCenterDataLinkageCreateEvent(TenantId, providerId, providerType, null, Id, nameof(Employee), $"{Code}-{Name}");
        }

        private AuthorCenterDataLinkageDeleteEvent GetAuthorCenterDataLinkageDeleteEvent(Guid providerId)
        {
            return new AuthorCenterDataLinkageDeleteEvent(TenantId, providerId, Id);
        }
        #endregion
    }
}
